package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.StockService;
import com.mall.shopping.ShoppingCartService;
import com.mall.shopping.dto.*;
import com.mall.user.UserService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: lin，qzb
 * @Date: 2020/7/10 20:55
 */

@RestController
@RequestMapping("shopping")
@Anoymous
public class TbShoppingCartController {

    @Reference(check = false)
    ShoppingCartService cartService;

    @Reference(check = false)
    UserService userService;

    @Reference(check = false)
    StockService stockService;


    @PostMapping("carts")
    public ResponseData addCartHandler(@RequestBody AddShoppingCartRequest request, HttpServletRequest req) {

        //校验用户信息是否被更改
        Cookie[] cookies = req.getCookies();
        String token = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(TokenIntercepter.ACCESS_TOKEN)){
                token = cookie.getValue();
                break;
            }
        }
        String uid = userService.getUid(token);

        if (!uid.equals(request.getUserId())) {
            return new ResponseUtil().setErrorMsg("用户信息不匹配");
        }

        //校验库存
        Boolean storage = stockService.isEnough(request.getProductId(), request.getProductNum());
        if (!storage){
            return new ResponseUtil().setErrorMsg("商品库存不足");
        }

        //添加购物车
        Boolean done = cartService.addGoodToCart(request);
        if (!done) {
            return new ResponseUtil().setErrorMsg("添加购物车失败，请重新添加");
        }
        return new ResponseUtil().setData("成功");
    }

    @GetMapping("carts")
    public ResponseData getCartListHandler(HttpServletRequest req) {
        Cookie[] cookies = req.getCookies();
        String token = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(TokenIntercepter.ACCESS_TOKEN)){
                token = cookie.getValue();
                break;
            }
        }
        String id = userService.getUid(token);
        Integer uid = Integer.parseInt(id);
        List<GetShoppingCartResponse> cartList = cartService.getCartList(uid);

        return new ResponseUtil().setData(cartList);

    }

    /**
     * 修改商品
     *
     * @return
     */
    @PutMapping("carts")
    public ResponseData updateCartHandler(@RequestBody UpdateCartNumRequest updateCartNumRequest, HttpServletRequest req) {
        //校验用户信息是否被更改
        /*String userInfo = (String) req.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        String uid = object.get("uid").toString();
        if (!uid.equals(request.getUserId())) {
            return new ResponseUtil().setErrorMsg("用户信息不匹配");
        }*/
        Boolean storage = stockService.isEnough(updateCartNumRequest.getProductId(), updateCartNumRequest.getProductNum());
        if (!storage){
            return new ResponseUtil().setErrorMsg("商品库存不足");
        }
        cartService.updateCart(updateCartNumRequest);
        return new ResponseUtil().setData("成功");
    }
    /**
     * 删除商品
     *
     * @return
     */
    @DeleteMapping("carts/{uid}/{pid}")
    public ResponseData deleteCartHandler(@PathVariable("uid") Long userId, @PathVariable("pid") Integer productId, HttpServletRequest req) {
        //校验用户信息是否被更改
        /*String userInfo = (String) req.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        String uid = object.get("uid").toString();
        if (!uid.equals(request.getUserId())) {
            return new ResponseUtil().setErrorMsg("用户信息不匹配");
        }*/
        DeleteCartItemRequest deleteCartItemRequest = new DeleteCartItemRequest();
        deleteCartItemRequest.setUserId(userId);
        deleteCartItemRequest.setProductId(productId);
        cartService.deleteCart(deleteCartItemRequest);
        return new ResponseUtil().setData("成功");
    }
    /**
     * 全选
     *
     * @return
     */
    @PutMapping("items")
    public ResponseData itemsCartHandler(@RequestBody ItemsCIartRequst itemsCartRequst, HttpServletRequest req) {
        //校验用户信息是否被更改
        /*String userInfo = (String) req.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        String uid = object.get("uid").toString();
        if (!uid.equals(request.getUserId())) {
            return new ResponseUtil().setErrorMsg("用户信息不匹配");
        }*/
        cartService.itemsCart(itemsCartRequst);
        return new ResponseUtil().setData("成功");

    }
    /**
     * 全选删除
     *
     * @return
     */
    @DeleteMapping("items/{uid}")
    public ResponseData deleteItemsCartHandler(@PathVariable("uid") Long userId, HttpServletRequest req) {
        //        //校验用户信息是否被更改
        /*String userInfo = (String) req.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        String uid = object.get("uid").toString();
        if (!uid.equals(request.getUserId())) {
            return new ResponseUtil().setErrorMsg("用户信息不匹配");
        }*/
        System.out.println("hhh");
        DeleteCheckedItemRequest deleteCheckedItemRequest = new DeleteCheckedItemRequest();
        deleteCheckedItemRequest.setUserId(userId);
        cartService.deleteItemsCart(deleteCheckedItemRequest);
        return new ResponseUtil().setData("成功");

    }
}